#!/usr/bin/env python
#
#  This file ...

# Mostly adapted from http://pysnippet.blogspot.com/2009/11/fuse-filesystem-in-userspace-part-1.html
#
#  by Mario Boikov

# -*- coding: utf-8 -*-  
import errno  
import fuse  
import os  
import sys 
import Tree
import Image
  
fuse.fuse_python_api = (0, 2)  
  
class ComeBackFat(fuse.Fuse):  
   def __init__(self, tree, *args, **kw):  
      fuse.Fuse.__init__(self, *args, **kw)  
      self.tree = tree  

   def getattr(self, path):  
      entry = self.tree.find(path)  

      if entry is None:  
         return -errno.ENOENT  
      else:  
         return entry.getAttribs()

   def readdir(self, path, offset):  
      for e in self.tree.find(path).getChildren():  
         yield fuse.Direntry(e.getName())  

   def open(self, path, flags):  
      # Only support for 'READ ONLY' flag  
      access_flags = os.O_RDONLY | os.O_WRONLY | os.O_RDWR  
      if flags & access_flags != os.O_RDONLY:  
         return -errno.EACCES  
      else:  
         return 0  

   def read(self, path, size, offset):
      entry = self.tree.find(path)
      if entry is None:
         print "*** :" + path + ": doesn't exist!!!"
         return -errno.ENOENT
      content = entry.getContent()
      file_size = len(content)  
      if offset < file_size:  
         if offset + size > file_size:  
            size = file_size - offset  
         return content[offset:offset+size]  
      else:  
         return ''  
  
def main(args):
   image = Image.Image(args[1])
   args.remove(args[1])

   # Initialise the image
   # Don't know how to handle file system arguments.
   #image = Image.Image("/media/imagesNStuff____/images/aines2GFlash/2GimageV2.dd")
   #image = Image.Image("/opt/images/USB4G_sylvia.dd")
   
   fileSystems = image.getFileSystems()
   if len(fileSystems) == 0:
      print "Error, no FAT file systems detected, nothing to show"
      return
     
   tree = Tree.Tree(fileSystems)
   
   fs = ComeBackFat(tree)  
   fs.parse(errex=1)  
   fs.main()

if __name__ == '__main__':  
   main(sys.argv)
